﻿#region Imports
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media.Imaging;
#endregion

namespace CommonUtilities.Converters
{
    /// <summary>
    /// Facilitates conversion of a <code>System.String</code> url into <code>System.Windows.Media.Imaging.BitmapImage</code>
    /// </summary>
    public class UrlImageConverter : IValueConverter
    {
        #region IValueConverter Members
        /// <summary>
        /// Converts a <code>System.String</code> URL into <code>System.Windows.Media.Imaging.BitmapImage</code>
        /// </summary>
        /// <param name="value">Source as <code>System.String</code></param>
        /// <param name="targetType">Type of the target (<code>System.Windows.Media.Imaging.BitmapImage</code>)</param>
        /// <param name="parameter">Conversion parameter</param>
        /// <param name="culture">UI culture of thread</param>
        /// <returns><code>System.String</code> URL converted to <code>System.Windows.Media.Imaging.BitmapImage</code></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string url = (string)value;
            BitmapImage bitmap = new BitmapImage();

            bitmap.BeginInit();
            bitmap.UriSource = new Uri(url, UriKind.Absolute);
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.EndInit();

            return bitmap;
        }

        /// <summary>
        /// NOT IMPLEMENTED (not required)
        /// </summary>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion IValueConverter Members
    }
}
